package com.ls.fw.web.core.servlet.listener;

import java.sql.Timestamp;
import java.util.Date;
import java.util.Hashtable;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import com.ls.fw.web.core.servlet.bean.SessionInfo;

/**
 * 用户统计
 * @author Defender
 * 2013-3-14
 */
public class OnlineListener implements HttpSessionListener{
 
	// 新建一个session时触发此操作
	public void sessionCreated(HttpSessionEvent se) {
 		System.out.println("新建一个session");
 		HttpSession session = se.getSession();  
        //如果是一次新的绘会话
        if(session.isNew()){
        	
            ServletContext application = session.getServletContext(); 
            //从在线列表中删除用户名 
            @SuppressWarnings("unchecked")
			Map<String,SessionInfo> online =  (Map<String,SessionInfo>)application.getAttribute("online"); 
            if(online==null){
            	online = new Hashtable<String ,SessionInfo>();
            }
            //获取session的id
            String sessionId = session.getId();
         // 取得登录的用户名  
            String userName = (String) session.getAttribute("userName"); 
            userName = (userName==null)?"游客":userName;
            SessionInfo user = new SessionInfo();
        	user.setLoginName(userName);
        	user.setSession(session);
            user.setSessionId(sessionId);
            user.setLoginTime(new Timestamp(new Date().getTime())) ;
            online.put(sessionId, user);
            application.setAttribute("online", online);
            System.out.println("OnlineListener:"+user.toString());
        }
	}

	// 销毁一个session时触发此操作
	public void sessionDestroyed(HttpSessionEvent se) {
		System.out.println("销毁一个session");
	 	HttpSession session = se.getSession(); 
        ServletContext application = session.getServletContext(); 
        @SuppressWarnings("unchecked")
		Map<String,SessionInfo> online =  (Map<String,SessionInfo>)application.getAttribute("online"); 
        if(online!=null){
        	//获取session的id
            String sessionId = session.getId();
            System.out.println("delete:"+sessionId);
        	online.remove(sessionId); 
        	application.setAttribute("online", online);
        }  
	}
 
}